import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/order_model/user_box_transfer_record_model.dart';
import 'package:yysk_app/model/order_model/user_collection_transfer_record_model.dart';
import 'package:yysk_app/model/order_model/user_prop_transfer_record_model.dart';
import 'package:yysk_app/model/tab_model.dart';
import 'package:yysk_app/net/api/order_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/nft_pages/transfer_record/transfer_out_detail_page.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/app_bar_back_widget.dart';
import 'package:yysk_app/widget/card_list_tile_widget.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/item_card_widget.dart';
import 'package:yysk_app/widget/lazy_network_image.dart';
import 'package:yysk_app/widget/refresh_and_scroll_widget.dart';
import 'package:yysk_app/widget/tab_widget.dart';

class TransferRecordPage extends StatefulWidget {
  static const path = '/transferRecordPage';
  const TransferRecordPage({super.key});
  @override
  State<StatefulWidget> createState() => _TransferRecordPage();
}

class _TransferRecordPage extends State<TransferRecordPage> {
  final ScrollController scrollController = ScrollController();
  final list = RxList<dynamic>([{}, {}, {}, {}]);
  late int pageNum = 1;
  late int pageSize = 10;
  late String type = '1'; //1藏品2盲盒3道具
  late String transferType = '1'; //1转出2接收
  List<UserCollectionTransferRecordItem> listCollection = [];
  List<UserBoxTransferRecordItem> listBox = [];
  List<UserPropTransferRecordItem> listProp = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (type == '1') {
      getCollectionOrder();
    } else if (type == '2') {
      getBoxOrder();
    } else {
      getPropOrder();
    }
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        // getFirstOrder(loadMore: true);
        if (type == '1') {
          getCollectionOrder(loadMore: true);
        } else if (type == '2') {
          getBoxOrder(loadMore: true);
        } else {
          getPropOrder(loadMore: true);
        }
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;

    return Scaffold(
      body: Container(
        color: AppColors.backgroundColorGreyF2,
        child: Column(
          children: [
            Expanded(
              child: Stack(
                children: [
                  Positioned(
                    right: 0,
                    bottom: 0,
                    child: ImageAssetWidget(
                      imageUrl: 'static/images/bottom_bg.png',
                      width: 258.px,
                      height: 74.px,
                    ),
                  ),
                  SizedBox(
                    width: context.width,
                    child: ImageAssetWidget(
                      width: 375.px,
                      height: 196.px,
                      alignment: Alignment.topCenter,
                      imageUrl: 'static/images/prop_transfer_bg.png',
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                    child: Column(
                      children: [
                        SizedBox(height: top),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            AppBarBackWidget(
                              context: context,
                              onBack: () {},
                              backgroundColor: AppColors.backgroundColorBlack,
                            ),
                            Expanded(
                              child: TabWidget(
                                isCurrentFontSize: 20,
                                notCurrentFontSize: 18,
                                fontFamily: 'CustomFont',
                                // rowMainAxisAlignment: 'spaceAround',
                                tabList: [
                                  TabModel(label: '藏品转赠', code: '1'),
                                  TabModel(label: '心愿盒转赠', code: '2'),
                                  TabModel(label: '道具转赠', code: '3'),
                                ],
                                onChanged: (val) {
                                  type = val;
                                  if (type == '1') {
                                    getCollectionOrder();
                                  } else if (type == '2') {
                                    getBoxOrder();
                                  } else {
                                    getPropOrder();
                                  }
                                },
                              ),
                            ),
                          ],
                        ),
                        Container(
                          padding: EdgeInsets.symmetric(horizontal: 70.px),
                          child: TabWidget(
                            isCurrentFontSize: 14,
                            notCurrentFontSize: 14,
                            rowMainAxisAlignment: 'spaceAround',
                            tabList: [
                              TabModel(label: '转出的', code: '1'),
                              TabModel(label: '接收的', code: '2'),
                            ],
                            onChanged: (val) {
                              transferType = val;
                              if (type == '1') {
                                getCollectionOrder();
                              } else if (type == '2') {
                                getBoxOrder();
                              } else {
                                getPropOrder();
                              }
                            },
                          ),
                        ),
                        Expanded(
                          child: Container(
                            padding: EdgeInsets.fromLTRB(12, 10, 12, 0),
                            child: RefreshAndScrollWidget(
                              onRefresh: _handleRefresh,
                              itemBuilder: (item, index) => _listItem(item),
                              itemCount:
                                  type == '1'
                                      ? listCollection.length
                                      : (type == '2'
                                          ? listBox.length
                                          : listProp.length),
                              items:
                                  type == '1'
                                      ? listCollection
                                      : (type == '2' ? listBox : listProp),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _listItem(item) {
    return GestureDetector(
      onTap: () {
        Get.toNamed(
          '${PropTransferOutPage.path}?type=$type&id=${item.id}',
          arguments: {
            'type': type,
            'id': item.id,
            'transferType': transferType,
          },
        );
      },
      child: Container(
        height: 190.px,
        padding: EdgeInsets.all(8.px),
        margin: EdgeInsets.only(bottom: 12.px),
        decoration: BoxDecoration(
          color: AppColors.backgroundColor,
          borderRadius: BorderRadius.circular(8.px),
        ),
        child: Column(
          children: [
            Row(
              children: [
                LazyImage(
                  imageUrl:
                      '${type == '1'
                          ? item?.coverImageUrl
                          : type == '2'
                          ? item?.boxCoverImageUrl
                          : item?.propImageUrl}',
                  height: 48.px,
                  width: 48.px,
                  borderRadius: 4.px,
                ),
                hiSpace(width: 4.px),
                Expanded(
                  // height: 48.px,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                        width: 180.px,
                        child: Text(
                          type == '1'
                              ? item.collectionName
                              : (type == '2' ? item.title : item.title),
                          style: TextStyle(
                            fontSize: 14,
                            color: AppColors.backgroundColorBlack,
                            fontFamily: 'CustomFont',
                          ),
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      // Text(
                      //   '#${item.id}',
                      //   style: TextStyle(
                      //     fontSize: 12,
                      //     color: AppColors.fontColor3D,
                      //   ),
                      // ),
                    ],
                  ),
                ),
                type == '1'
                    ? Container(
                      alignment: Alignment.centerRight,
                      margin: EdgeInsets.only(right: 8.px),
                      height: 20.px,
                      // width: 75.px,
                      padding: EdgeInsets.only(right: 8.px, left: 8.px),
                      constraints: BoxConstraints(minWidth: 60.px),
                      decoration: BoxDecoration(
                        color: Color.fromRGBO(227, 231, 226, 1),
                        borderRadius: BorderRadius.circular(3.px),
                      ),
                      child: Center(
                        child: Text(
                          '${item.platform == 'INTERNAL' ? '内部' : '臻藏'}转赠',
                          style: TextStyle(
                            fontSize: 12,
                            color: AppColors.fontColorGreen,
                            fontFamily: 'CustomFont',
                          ),
                        ),
                      ),
                    )
                    : SizedBox(),
              ],
            ),
            _buildDetail(item),
          ],
        ),
      ),
    );
  }

  Widget _buildDetail(item) {
    return ItemCardWidget(
      child: Column(
        children: [
          CardListTileWidget(
            label: '数量',
            value: '*${item.count}',
            margin: EdgeInsets.only(top: 10.px),
          ),
          CardListTileWidget(
            label: '发送方',
            value:
                '${type == '1' ? item.sendAddress : (type == '2' ? item.sendUserAccount : item.sendUserAccount)}',
            canCopy: true,
            margin: EdgeInsets.only(top: 10.px),
          ),
          CardListTileWidget(
            label: '接收方',
            value:
                '${type == '1' ? item.receiveAddress : (type == '2' ? item.receiveUserAccount : item.receiveUserAccount)}',
            canCopy: true,
            margin: EdgeInsets.only(top: 10.px),
          ),
          CardListTileWidget(
            label: '转赠时间',
            value: '${item.createTime}',
            margin: EdgeInsets.only(top: 10.px),
          ),
        ],
      ),
    );
  }

  Future<void> _handleRefresh() async {
    if (type == '1') {
      getCollectionOrder();
    } else if (type == '2') {
      getBoxOrder();
    } else {
      getPropOrder();
    }
    return;
  }

  //藏品流转
  Future<void> getCollectionOrder({loadMore = false}) async {
    if (loadMore) {
      pageNum++;
    } else {
      pageNum = 1;
    }

    var params = {
      'pageNum': pageNum,
      'pageSize': pageSize,
      'purchase': transferType == '1' ? false : true,
    };

    try {
      await http.netFetch<UserCollectionTransferRecordModel>(
        OrderUrl.userCollectionTransferRecord,
        params: params,
        success: (result) {
          List<UserCollectionTransferRecordItem> list = result.data?.list ?? [];
          if (loadMore && list.isEmpty) {
            pageNum--;
          }
          if (!loadMore) {
            setState(() {
              listCollection = [];
            });
          }
          setState(() {
            listCollection = [...listCollection, ...list];
          });
        },
      );
    } catch (e) {
      debugPrint(e.toString());
      if (loadMore) {
        pageNum--;
      }
    }
  }

  //盲盒流转
  Future<void> getBoxOrder({loadMore = false}) async {
    if (loadMore) {
      pageNum++;
    } else {
      pageNum = 1;
    }

    var params = {
      'pageNum': pageNum,
      'pageSize': pageSize,
      'purchase': transferType == '1' ? false : true,
    };

    try {
      await http.netFetch<UserBoxTransferRecordModel>(
        OrderUrl.userBoxTransferRecord,
        params: params,
        success: (result) {
          List<UserBoxTransferRecordItem> list = result.data?.list ?? [];
          if (loadMore && list.isEmpty) {
            pageNum--;
          }
          if (!loadMore) {
            setState(() {
              listBox = [];
            });
          }
          setState(() {
            listBox = [...listBox, ...list];
          });
        },
      );
    } catch (e) {
      debugPrint(e.toString());
      if (loadMore) {
        pageNum--;
      }
    }
  }

  //道具流转
  Future<void> getPropOrder({loadMore = false}) async {
    if (loadMore) {
      pageNum++;
    } else {
      pageNum = 1;
    }

    var params = {
      'pageNum': pageNum,
      'pageSize': pageSize,
      'purchase': transferType == '1' ? false : true,
    };

    try {
      await http.netFetch<UserPropTransferRecordModel>(
        OrderUrl.userPropTransferRecord,
        params: params,
        success: (result) {
          List<UserPropTransferRecordItem> list = result.data?.list ?? [];
          if (loadMore && list.isEmpty) {
            pageNum--;
          }
          if (!loadMore) {
            setState(() {
              listProp = [];
            });
          }
          setState(() {
            listProp = [...listProp, ...list];
          });
        },
      );
    } catch (e) {
      debugPrint(e.toString());
      if (loadMore) {
        pageNum--;
      }
    }
  }
}
